package dao;

import java.util.Calendar;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.TypedQuery;

import util.StringUtil;
import entity.Client;

@JPA
@Stateless
public class JPAClientDAO extends GenericJPADAO<Client> implements ClientDAO {
	
	@Override
	public int selectClientCountByNameOrLastnamePart(String searchString) {
		TypedQuery<Long> query = em.createNamedQuery(
				"Client.selectCountByNameOrLastnamePart", Long.class)
				.setParameter("partname", "%" + searchString + "%");
		return query.getSingleResult().intValue();
	}
	
	@Override
	public List<Client> selectClientsByNameOrLastnamePartPaged(String searchString, int startAt, int resultsPerPage) {
		TypedQuery<Client> query = em.createNamedQuery(
				"Client.selectByNameOrLastnamePart", Client.class)
				.setParameter("partname", "%" + searchString + "%");
		query.setFirstResult(startAt);
		query.setMaxResults(resultsPerPage);
		return query.getResultList();		
	}	

	@Override
	public void populateWithTestData(int amount) {
		for (int i = 0; i < amount; i++) {			
			Client client = new Client(StringUtil.createRandomString(5), StringUtil.createRandomString(5), Calendar.getInstance(), "11111111");
			em.persist(client);
			if (i % 100 == 0) {
				em.flush();
				em.clear();
			}
		}
	}

}